<?php


global $AppUI, $project_id, $df, $canEdit, $m, $tab, $canViewTaskFee, $canCreateTasks, $hasRoleFfifaMana, $canViewExpense;

require_once($AppUI->getModuleClass('companies'));
require_once($AppUI->getModuleClass('suppliers'));
require_once($AppUI->getModuleClass('items'));
require_once($AppUI->getModuleClass('tasks'));
require_once($AppUI->getModuleClass('projects'));
require_once($AppUI->getMasterDataClass('mdtype'));
require_once($AppUI->getMasterDataClass('mdstatus'));

$df = $AppUI->getPref('SHDATEFORMAT');

$perms =& $AppUI->acl();
$canAccessTask = $perms->checkModuleItem( 'tasks', 'access');
$canEditTask = $perms->checkModuleItem( 'tasks', 'edit');
$canDeleteTask = $perms->checkModuleItem( 'tasks', 'delete');
$canAddLog = $perms->checkModuleItem( 'timecard', 'add');
$canEditQuotation = $perms->checkModuleItem( 'quotations', 'edit');
$canEditSalesAmount = $perms->checkModuleItem('taskfee', 'edit');
$msg = NULL;
if (!$canAccessTask) {
	$msg = 'You do not have permission to list these tasks';
}

if ($msg != NULL) {
	$AppUI->setMsg($msg, UI_MSG_ERROR);
	$AppUI->redirect();
}

if (isset($_POST['resetAction'])) {
	$AppUI->unsetPOST('TASK_POST');
}
else {
	if (count($_POST) > 0) {
		$AppUI->savePOST('TASK_POST');
	}
	else {
		$_POST = $AppUI->getPOST('TASK_POST');
	}
}
$task_not_quotation = intval( dPgetParam( $_GET, 'task_not_quotation', 0 ) );
////edit quotation va khong co quyen edit Tasks => chi duoc xem tasks chua link voi quotation
//if ($canEditQuotation && !$canEditTask) {
//	$task_not_quotation = 1;
//}


$page_offset = intval( dPgetParam( $_GET, 'page_offset', 0 ) );
//$page_limit = intval( dPgetParam( $_POST, 'page_limit', $AppUI->getPref('PAGELIMIT', 5) ) );
$page_limit = intval( dPgetParam( $_POST, 'page_limit', 10));
$status_id = intval( dPgetParam( $_POST, 'status_id', 0 ) );
$item_type = intval( dPgetParam( $_POST, 'item_type', 0 ) );
$customer = intval( dPgetParam( $_POST, 'customer', 0 ) );
$project_shipping_type = intval( dPgetParam( $_POST, 'project_shipping_type', 0 ) );
$keyword = dPgetParam( $_POST, 'keyword', '' );
$project_name = dPgetParam( $_POST, 'project_name', '' );
$project_code = dPgetParam( $_POST, 'project_code', '' );
$from_date = dPgetParam( $_POST, 'from_date', '' );
$to_date = dPgetParam( $_POST, 'to_date', '' );
//do search
$q = new DBQuery();
//$q->dropTemp('pitems, wunit, vunit, qunit, amounts');
//$q->exec();
//$q->clear();
//
//$q->createTemp('wunit');
//$q->addTable('md_unit');
//$q->addQuery('unit_id as wunit_id, unit_name as wunit_name');
//$q->exec();
//$q->clear();
//
//$q  = new DBQuery;
//$q->createTemp('qunit');
//$q->addTable('md_unit');
//$q->addQuery('unit_id as qunit_id, unit_name as qunit_name');
//$q->exec();
//$q->clear();
//
//// Volumn Unit
//$q  = new DBQuery;
//$q->createTemp('vunit');
//$q->addTable('md_unit');
//$q->addQuery('unit_id as vunit_id, unit_name as vunit_name');
//$q->exec();
//$q->clear();

$q->createTemp('pitems');
$q->addTable('items');
//$q->leftJoin('wunit', 'wu', 'item_weight_unit = wu.wunit_id');
//$q->leftJoin('qunit', 'qu', 'item_quantity_unit = qu.qunit_id');
//$q->leftJoin('vunit', 'vu', 'item_volume_unit = vu.vunit_id');
if ($item_type > 0) {
	$q->addWhere("item_type1 = $item_type");
}
$q->exec();
$q->clear();

//main query for tasks
$q->addTable('tasks');
$q->innerJoin('projects', 'pro', 'project_id = task_project');
$q->innerJoin('pitems', 'pi', 'item_id = task_item');
$q->leftJoin('md_unit', 'u', 'tasks.task_unit = u.unit_id');
$q->leftJoin('quotations', 'q', 'quote_id = task_quotation ');
$q->addWhere('task_project = ' . $project_id);
if ($task_not_quotation > 0) {
	$q->addWhere('(task_quotation IS NULL or task_quotation = 0)');
}
//if user's role is FFIA_Staff, load all tasks but only show button new log for user costcenter task
//if user's role is Operation then filter tasks belong to user's cost center
$needCheckCostCenter = $perms->userHasRole($AppUI->user_id, "Operation");
if ($needCheckCostCenter) {
	$q->addWhere("task_costcenter = {$AppUI->user_costcenter}");
}
$needCheckCostCenter = $perms->userHasRole($AppUI->user_id, "Operation") || $perms->userHasRole($AppUI->user_id, "FFIA_Staff");

$q->addWhere('task_project = ' . $project_id);
$q->addOrder('task_start_date desc, task_name');
//$q->setLimit($page_limit, $page_offset);
$qTotal = $q->prepare();
$q->addQuery('distinct tasks.*, pro.*, q.*, pi.*, u.unit_name');
$tasks = $q->loadList();
// Load Object Status
$objMD = new CMdStatus();
$statList = $objMD->getStatusList('Reference');

$objMD = new CMdType();
$itemtypeList = $objMD->getTypeList('ItemType1');

$objMD = new CCompany();
$cusList = $objMD->getAllowedRecords($AppUI->user_id, 'company_id, company_name', 'company_name');
$cusList = arrayMerge(array('0'=>"" . $AppUI->_(''). ""), $cusList);

?>
<table border="0" cellpadding="2" cellspacing="0" width="100%" class="infopanel">
<form name="frmFilter" action="index.php" method="get">
<tr>
	<td width="98%">
	<?php
	if ($m == 'projects' && $canCreateTasks && $canEdit){
		echo "<input type='button' value='New Task' onclick='goNewTask($project_id)' class='button'/>";
	} else {
		echo "&nbsp;";
	}?>
	</td>
	<td width="1%">
		<input id="idHIA" type="checkbox" name="task_not_quotation" <?=$task_not_quotation > 0?'checked':''?>
			value="1" onchange="document.frmFilter.submit()">
	</td>
	<td nowrap="nowrap"><label for="idHC"><?=$AppUI->_('Task not link quotation')?></label></td>
	<td><img src="images/blank.gif" width="8"></td>
</tr>
<input type="hidden" name="m" value="projects"/>
<input type="hidden" name="a" value="view"/>
<input type="hidden" name="project_id" value="<?=$project_id?>"/>
<input type="hidden" name="tab" value="<?=$tab?>"/>
</form>
</table>
<table id="idTasksList" class="list" cellspacing="0" cellpadding="2" border="0" width="100%">
		<tr class="<?=($i % 2 == 0) ? "second" : "first" ?>">
			<th >&nbsp;</th>
			<th >&nbsp;</th>
			<th align="right"><?=$AppUI->_('%')?></th>
			<th ><?=$AppUI->_('Code')?></th>
			<th ><?=$AppUI->_('Name')?></th>
			<th ><?=$AppUI->_('Quotation')?></th>
			<?php if ($canViewExpense):?>
			<th ><?=$AppUI->_('Expense Amount')?></th>
			<?php endif;?>
			<?php if ($canViewTaskFee)
				echo "<th >". $AppUI->_('Sales Amount'). "</th>"
			?>
			<?php if ($canEditSalesAmount):?>
			<th ><?=$AppUI->_('VAT Amount')?></th>
			<th ><?=$AppUI->_('VAT')?></th>
			<?php endif;?>
			<th ><?=$AppUI->_('Quantity')?></th>
			<th ><?=$AppUI->_('Unit')?></th>
			<th ><?=$AppUI->_('Start date')?></th>
			<th ><?=$AppUI->_('End date')?></th>
			<th ><?=$AppUI->_('Remarks')?></th>
			<?php if ($canDeleteTask && $canEdit): ?>
			<th ><?=$AppUI->_('Delete')?></th>
			<th ><?=$AppUI->_('Force')?></th>
			<?php endif;?>
		</tr>
<?php
if (is_array($tasks) && count($tasks) > 0) {
	$totalRows = 0;
	$qTotal = str_ireplace('select *', 'select count(*) as total_rows', $qTotal);
	$tmp = db_loadList($qTotal);
	$totalRows = $tmp[0]['total_rows'];

	require_once($AppUI->getLibraryClass('codeigniter/pagination'));
	$pagination = new CI_Pagination();
	$config = array(
		'base_url' => '?m=projects&tab=1',
		'total_rows' => $totalRows,
		'per_page' => $page_limit

	);
	$pagination->initialize($config);
	$i = 0;
	?>

	<script type="text/javascript">
		function submitForm(offset) {
			document.reportFrm.offset.value = offset;
			document.reportFrm.submit();
		}
	</script>
	<?
	$sumAmounts = 0.00;
	$$taskFee = 0.00;
	foreach ($tasks as $row) {
		$sumAmounts += $row['sum_amount'];
		$taskFee += $row['task_fee'] > 0 ? $row['task_fee'] : 0;
		$i++;
		$start_date = new CDate($row['task_start_date']);
		$end_date = new CDate($row['task_end_date']);
		$my_cc_task = $needCheckCostCenter ? $row['task_costcenter'] == $AppUI->user_costcenter : TRUE;
		?>
		<tr class="<?=($i % 2 == 0) ? "second" : "first" ?>">
			<td align='center' onClick="showTask(<?=$row['task_id']?>)">
				<?if($row['task_is_complete'] < 1 &&( ($canAddLog && $my_cc_task))){ ?>
					<a href="?m=timecard&a=vw_newlog&project_id=<?=$row['task_project']?>&task_id=<?=$row['task_id']?>"><image src="images/add_log.gif" border="0" alt="Add log"/></a>
				<?} else {?>
					<image src="images/noadd_log.gif" border="0" alt="No Add log"/>
				<?}?>
			</td>
			<td align='center' onClick="showTask(<?=$row['task_id']?>)">
				<?if($row['task_is_complete'] < 1 && $canEditTask && $my_cc_task){ ?>
					<a href="?m=tasks&a=simpleaddedit&task_id=<?=$row['task_id']?>"><image src="images/edit.gif" border="0" alt="Edit"/></a>
				<?} else {?>
					<image src="images/noedit_task.gif" border="0" alt="No Edit"/>
				<?}?>

			</td>
			<td align='right' onClick="showTask(<?=$row['task_id']?>)"><?=$row['task_is_complete'] == 0 ? (@$row['task_percent_complete'] . '%') : '<font color="Green">Completed</font>'?></td>
			<td onClick="showTask(<?=$row['task_id']?>)"><?=$row['item_code']?></td>
			<td onClick="showTask(<?=$row['task_id']?>)"><?=$row['task_name']?></td>
			<td onClick="showTask(<?=$row['task_id']?>)"><?=$row['quote_name']?></td>
			<?php if ($canViewExpense):?>
			<td onClick="showTask(<?=$row['task_id']?>)"align='right'><?=currencyFormat($row['sum_amount'], TRUE)?></td>
			<?php endif;?>
			<?php if ($canViewTaskFee){
				$obj->task_fee = $obj->task_fee == -1 ? 0 : $obj->task_fee;
				echo "<td nowrap='nowrap'>";
				if ($canEditSalesAmount && $row['task_is_complete'] == 1) {
					echo "<div style='float:left'>";
					showIconLink('images/edit.gif', 'js:return openSalesAmountDialog('.$row['task_id'].', \''. currencyFormat($row['task_fee'], $row['project_currency']) . '\', \''. addslashes($row['task_name']) .'\')', 'Edit');
					echo "</div>";
				}
				echo "<div style='float:right'>" . currencyFormat($row['task_fee'], $row['project_currency'] == CURRENCY_VND_VALUE) . "</div>";
				echo "</td>";
			}
			?>
			<?php if ($canEditSalesAmount):?>
			<td align='right'><?=currencyFormat($row['task_vat_amount'], $row['project_currency'])?></td>
			<td align='right'>
			<?php if (intval($row['task_vat']) != 0):?>
			<div style='float:left'><?=$row['task_vat'] > 0 ? dPshowImage("images/sin.gif") : dPshowImage("images/sout.gif")?></div>
			<div style='float:right'><?=number_format($row['task_vat'] > 0 ? $row['task_vat'] : -1 * $row['task_vat'])?>%</div>
			<?php endif;?>
			<?php endif;?>
			<td align='right'><?=number_format($row['task_figure'], 2)?></td>
			<td align='right'><?=$row['unit_name']?></td>
			<td >
				<div style="float:left"><?=$start_date->format($df)?></div><br/>
				<div style="float:right"><?=@$row['task_start_time']?></div>
			</td>
			<td >
				<div style="float:left"><?=$end_date->format($df)?></div><br/>
				<div style="float:right"><?=@$row['task_end_time']?></div>
			</td>
			<td ><?=$row['task_description']?></td>
			<?php if($canDeleteTask && $row['task_is_complete'] < 1 && $my_cc_task) {
			echo "<td align='center'>";
				showIconLink('images/delete.gif', 'js:doDeleteTask('.$row["task_id"]. ', \''.addslashes($row["task_name"]).'\')', 'Delete');
			echo "</td>";
			}
			?>
			<?php if($canDeleteTask && $row['task_is_complete'] < 1 && $my_cc_task) {
			echo "<td align='center'>";
				showIconLink('images/force_complete.gif', 'js:doForceCompleteTask('.$row["task_id"]. ', \''.addslashes($row["task_name"]).'\')', 'Force complete');
			echo "</td>";
			}
			?>
		</tr>
		<?
	}
	?>
	<tr>
		<th colspan="6" align="right">Total: </th>
		<?php if ($canViewExpense):?>
		<th align="right"><?=number_format($sumAmounts, 2)?></th>
		<?php endif;?>
		<?php if ($canViewTaskFee) { ?>
		<th align="right"><?=number_format($taskFee, 2)?></th>
		<?}?>
		<th colspan="100%"></th>
	</tr>
	</table>

	<?
} else {
	showEmptyRow('1', 'second', 'Not found any tasks', '100%');
}

?>
</table>
<script>
	Calendar.enabled = true;

	Table("idTasksList").setNormalHover(1);

	function showTask(id)
	{
		location.href = "index.php?m=tasks&a=view&task_id=" + id;
	}

	function doSearch(frm) {
		frm.action = '?m=projects&tab=1&suppressHeaders=0';
		frm.submit();
	}

	function doExport(frm) {
		//frm.action = '?m=reports&a=do_r_reference&suppressHeaders=1';
		//frm.submit();
	}

	function doDeleteTask(id, name)	{
		if (confirm( "Do you want to delete "+ name)) {
			$('idTaskId').value = id;
			f = $('MdFormDeleteTask');
			f.del.value = id;
			f.submit();
		}
	}

	function doForceCompleteTask(id, name)
	{
		if (confirm( "Do you want to force complete task: "+ name)) {
			location.href = "index.php?m=tasks&a=do_force_complete&task_id=" + id;
		}
	}
</script>
<form name="MdFormDeleteTask" id="MdFormDeleteTask" action="?m=tasks&a=do_delete" method="post">
	<input type="hidden" name="dosql" value ="do_delete" />
	<input type="hidden" id="idTaskId" name="task_id" value ="" />
	<input type="hidden" name="del" value ="" />
</form>
<?php if($canEditSalesAmount):?>
<div id="idSalesAmountDialog" class="popup" style="width: 200px; visibility: hidden; display: none;">
	<form action="?m=tasks&a=do_edit_salesamount" method="POST">
	<input type="hidden" name="task_id" id="saTaskId" value=""/>
	<table width="100%" cellspacing="0" cellpadding="4" border="0" class="subinfopanel">
		<tr>
			<th colspan="2" id="saTaskName">Sales amount</th>
		</tr>
		<tr>
			<td align="right" nowrap="nowrap"> * <?=$AppUI->_( 'Sales amount' )?></td>
			<td nowrap="nowrap">
				<input id="idSalesAmountInput" name="sales_amount_input" type="text" style="width: 80px; text-align: right" value="" onkeyup="return (currencyFormat(this, ',', '.', event))"/>
			</td>
		</tr>
		<tr>
			<td colspan="100%">
				<input type="submit" value="<?=$AppUI->_('Save')?>" name="btnSave"/>
				<input type="button" value="<?=$AppUI->_('Cancel')?>" name="btnCancel" onclick="Dialog('idSalesAmountDialog').hide();"/>
			</td>
		</tr>
	</table>
	</form>
</div>
<?php endif;?>